package com.happe.foodeasy.helper;

import com.happe.foodeasy.helper.annotation.FatherEntity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

/**
 * This class is used to generate sql for dao.
 * Created by wubin on 2016-05-12.
 */
@Component
public class DaoSqlHelper {
    /**
     * This method is used to generate insert database sql, and use the placeholder ?.
     * the fundamental style is insert into tableName (columnName1, columnName2) values (?, ?);
     *
     * @param tableName the name of table.
     * @param params    the column name of target table.
     * @return the insert sql.
     */
    public String generateInsertSqlJustColumn(String tableName, String[] params) {
        String sql = "insert into " + tableName + " (";

        for (String key : params) {
            sql += key + ",";
        }
        sql = sql.substring(0, sql.length() - 1) + ")";

        return sql + " values " + generatePlaceHolder(params.length);
    }

    private String generatePlaceHolder(int size) {
        String placeHolder = "(";
        for (int i = 0; i < size; i++) {
            placeHolder += "? ,";
        }
        placeHolder = placeHolder.substring(0, placeHolder.length() - 1) + ")";
        return placeHolder;
    }

    /**
     * This method is used to generate select sql, use the placeholder ? to occupy the position
     * of value, and just has the "and" keyboard, for example: select * from tableName from columnName1 = ? and
     * columnName2 = ?;  This is the style of final sql.
     *
     * @param tableName   The name of table.
     * @param columnNames The all column of table
     * @return The select sql.
     */
    public String generateSelectSqlJustColumn(String tableName, String[] columnNames) {
        String sql = "select * from " + tableName;
        if (columnNames == null) {
            return sql;
        }

        sql += " where ";
        for (String name : columnNames) {
            sql += name + " = ? and ";
        }
        sql = sql.substring(0, sql.lastIndexOf("and"));
        return sql;
    }
}
